import { GridContent } from '@ant-design/pro-layout';
import React, { forwardRef, useEffect, useState } from 'react';
import { Input, Form, Modal } from 'antd';
import CodeMirrorShell from '@/pages/global/codeMirrorShell';
// import { parse } from 'qs';
const { TextArea } = Input;

// eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/ban-types
const Files: React.ForwardRefExoticComponent<
  React.PropsWithoutRef<{
    getForm: Function;
    open: boolean;
    onCancel: Function;
    onOk: Function;
    modelData?: PRO.files;
  }> &
    React.RefAttributes<unknown>
> = forwardRef(
  (props: {
    getForm: Function;
    open: boolean;
    onCancel: Function;
    onOk: Function;
    modelData?: PRO.files;
  }) => {
    const [form] = Form.useForm();
    const [showCode, setShowCode] = useState(false);

    const getRandomString = (len: number) => {
      const _charStr = 'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789';
      // eslint-disable-next-line prefer-const
      let min = 0,
        max = _charStr.length - 1,
        _str = '';
      //判断是否指定长度，否则默认长度为15
      // eslint-disable-next-line no-param-reassign
      len = len || 15;
      //循环生成字符串
      for (let i = 0, index; i < len; i++) {
        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        index = RandomIndex(min, max, i);
        _str += _charStr[index];
      }
      return _str;
    };
    const RandomIndex = (min: number, max: number, i: number) => {
      const _charStr = 'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789';
      let index = Math.floor(Math.random() * (max - min + 1) + min),
        // eslint-disable-next-line prefer-const
        numStart = _charStr.length - 10;
      //如果字符串第一位是数字，则递归重新获取
      if (i == 0 && index >= numStart) {
        index = RandomIndex(min, max, i);
      }
      //返回最终索引值
      return index;
    };
    useEffect(() => {
      form.setFieldsValue(props.modelData);
    }, [form, props.modelData, props.open]);
    const GetFormData = async () => {
      return new Promise((resolve, reject) => {
        form
          .validateFields()
          .then(() => {
            const data = form.getFieldsValue();
            if (!data.unique_id) {
              data.unique_id = getRandomString(15);
            }
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    };

    return (
      <GridContent>
        <CodeMirrorShell
          open={showCode}
          defaultValue={props.modelData?.content}
          onOk={() => {
            setShowCode(false);
          }}
          onchange={(code: any) => {
            console.log(code.doc.getValue());
            form.setFieldValue('content', code.doc.getValue());
          }}
          okCancel={() => {
            setShowCode(false);
          }}
        />
        <Modal
          onCancel={() => {
            props.onCancel();
          }}
          open={props.open}
          onOk={() => {
            GetFormData()
              .then((data: any) => {
                props.onOk(data, form);
              })
              .catch((err) => {
                console.log(err);
              });
          }}
        >
          <Form
            form={form}
            name="basic"
            labelCol={{
              span: 6,
            }}
            wrapperCol={{
              span: 16,
            }}
            initialValues={props.modelData}
            // onFinish={async (values) => {
            //   await handleSubmit(values as PRO.Project);
            // }}
            // onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              label="文件路径"
              name="path"
              tooltip="请输入文件路径,此路径相对于项目的路径,在运行时此文件会在对应的路径生成"
              rules={[
                {
                  required: true,
                  message: '请输入文件路径!',
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              hidden={true}
              label="id"
              name="id"
              rules={[
                {
                  required: false,
                  message: '请输入步骤名称!',
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="文件内容"
              name="content"
              tooltip="可以是需要执行的文件,比如DockerFile or k8s file"
              rules={[
                {
                  required: true,
                  message: '请输入文件内容',
                },
              ]}
            >
              <TextArea
                onClick={() => {
                  setShowCode(true);
                }}
                rows={15}
              />
            </Form.Item>

            <Form.Item
              label="参数json"
              name="template_args"
              tooltip="参数会替换模板中的定义的模板"
              rules={[
                {
                  required: false,
                  message: '命令中的参数json!',
                },
              ]}
            >
              <TextArea rows={4} />
            </Form.Item>

            <Form.Item
              hidden={true}
              label="unique_id"
              name="unique_id"
              tooltip="参数会替换模板中的定义的模板"
              rules={[
                {
                  required: false,
                  message: '命令中的参数json!',
                },
              ]}
            >
              <Input />
            </Form.Item>
          </Form>
        </Modal>
      </GridContent>
    );
  },
);

export default Files;
